﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Communergy.Common;
using System.Diagnostics;
using CommunergyUploader.WeatherWCFService;


namespace CommunergyUploader
{
    public class CurrentCostUploadToWeatherWCF: IRealtimeRepository
    {
 
        int maxRecords = 50;

        #region IRealtimeRepository Members

        public void Insert_ElectricityRealtime(string meterId, List<RealtimeEnergyReading> realtimeEnergyReadings)
        {
            Trace.WriteLine(string.Format("{0} records received", realtimeEnergyReadings.Count));




            var client = new WeatherServiceClient();
            client.Open();
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            

             int recordsToUpload = (int)realtimeEnergyReadings.Count;
            int chunks = (recordsToUpload / maxRecords + 1);
            int recordsUploaded = 0;
            for (int chunk = 0; chunk < chunks; chunk++)
            {

                int startPosition = chunk * maxRecords;

                var readingsToSend = (from r in realtimeEnergyReadings
                                      select new CurrentCostReading
                                      {
                                          ReadingDateTime = new DateTime(r.ReadingDateTime.Year, r.ReadingDateTime.Month, r.ReadingDateTime.Day, r.ReadingDateTime.Hour, r.ReadingDateTime.Minute, r.ReadingDateTime.Second),
                                          Watts = r.Watts
                                      }).Skip(startPosition).Take(maxRecords).ToArray();
                Trace.WriteLine(string.Format("Sending {1} readings to {0}", client.Endpoint.Address.Uri.ToString(), readingsToSend.Length));
                client.SaveCurrentCostReadings(readingsToSend);

            }

            client.Close();
            stopwatch.Stop();
            Trace.WriteLine(string.Format("ReadingTotal sent in {0} ", stopwatch.Elapsed.ToString()));
        }

        #endregion

        #region IRealtimeRepository Members


        public List<RealtimeEnergyReading> Get_ElectricityRealtime(string meterId, DateTime dateFrom, DateTime dateTo)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IRealtimeRepository Members


        public RealtimeEnergyReading GetLastElectricityRealtime(string meterId)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IRealtimeRepository Members


        public HistoricalEnergyReading GetCumulativeElectricityRealtime(string meterId, DateTime dateFrom, DateTime dateTo)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
